package com.jinghao.tws.service.nos;

import java.io.File;
import java.net.URL;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinghao.tws.util.PropertiesManager;
import com.netease.cloud.ClientConfiguration;
import com.netease.cloud.ClientException;
import com.netease.cloud.ServiceException;
import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.GeneratePresignedUrlRequest;
import com.netease.cloud.services.nos.transfer.TransferManager;
import com.netease.cloud.services.nos.transfer.Upload;
import com.netease.cloud.services.nos.transfer.model.UploadResult;

@Service
public class NosService {
	public static final Logger logger = LoggerFactory.getLogger(NosService.class);
	@Autowired
	private PropertiesManager propertiesManager;

	public TransferManager getTransferManager() {
		return new TransferManager(getNosClient());
	}

	public NosClient getNosClient() {
		Credentials credentials = new BasicCredentials(getAccessKey(), getSecretKey());
		ClientConfiguration conf = new ClientConfiguration();
		// 设置 NosClient 使用的最大连接数
		conf.setMaxConnections(200);
		// 设置 socket 超时时间
		conf.setSocketTimeout(10000);
		// 设置失败请求重试次数
		conf.setMaxErrorRetry(2);
		NosClient nosClient = new NosClient(credentials, conf);
		nosClient.setEndpoint(getEndPoint());
		return nosClient;
	}
	
	public boolean uploadObject(String localFilePath, String objectName) {
		try {
			logger.info("fileUploadToCloudNos [" + localFilePath + "] objectName:" + objectName);
			TransferManager transferManager = getTransferManager();
			Upload upload = transferManager.upload(getBucketName(), objectName, new File(localFilePath));
			UploadResult result = upload.waitForUploadResult();
			logger.info("fileUploadToCloudNos [" + localFilePath + "] bucket:" + result.getBucketName() 
				+ " key:" + result.getKey() + " eTag:" + result.getETag() + " versionId:" + result.getVersionId());
			return true;
		} catch (ServiceException e){
			logger.error("Error Message:    " + e.getMessage());
			logger.error("HTTP Status Code: " + e.getStatusCode());
			logger.error("NOS Error Code:   " + e.getErrorCode());
			logger.error("Error Type:       " + e.getErrorType());
			logger.error("Request ID:       " + e.getRequestId());
		} catch(ClientException e){
			logger.error("Error Message: " + e.getMessage());
		} catch (Exception e) {
			logger.error("fileUploadToCloudNos failed " + e.getMessage());
		}
		
		logger.error("fileUploadToCloudNos upload  " + objectName + " failed");
		return false;
	}

	public String getObjectUrl(String objectName) {
		logger.info("getObjectUrl " + objectName);
		if (StringUtils.isBlank(objectName)) {
			return null;
		}
		NosClient nosClient = getNosClient();
		if (!getNosClient().doesObjectExist(getBucketName(), objectName)) {
			logger.info("getObjectUrl " + objectName + " object not found!");
			return null;
		}
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(getBucketName(), objectName);
        //setExpiration为当前时间点+过期时间，设置可下载URL的过期时间。默认过期时间为1天。
        generatePresignedUrlRequest.setExpiration(new Date(System.currentTimeMillis()+3600*1000));
        URL url = nosClient.generatePresignedUrl(generatePresignedUrlRequest);
        if (null == url) {
        	logger.info("getObjectUrl " + objectName + " object url null");
        	return null;
        }
        logger.info("getObjectUrl " + objectName + " object url " + url.toString());
        return url.toString();
	}
	
	private String getEndPoint() {
		return propertiesManager.getString("nos-end-point");
	}
	
	private String getBucketName() {
		return propertiesManager.getString("nos-bucket-name");
	}
	
	private String getAccessKey() {
		return propertiesManager.getString("nos-access-key");
	}
	
	private String getSecretKey() {
		return propertiesManager.getString("nos-secret-key");
	}
}
